package lbframework.bean.textField;

import java.awt.Color;
import java.awt.Container;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.MaskFormatter;
import javax.swing.undo.UndoManager;
import lbframework.classe.Util;
import lbframework.classe.LBException;
import lbframework.bean.field.LBPlainDocument;
import lbframework.bean.internalFrame.LBInternalFrame;

public class LBTextField extends javax.swing.JFormattedTextField {

    public final static String MASK_TEXTO = "Texto";
    public final static String MASK_DATA = "Data";
    public final static String MASK_MESANO = "Mês/Ano";
    public final static String MASK_NUMERO = "Numero";
    public final static String MASK_DECIMAL0 = "Decimal 0";
    public final static String MASK_DECIMAL1 = "Decimal 1";
    public final static String MASK_DECIMAL2 = "Decimal 2";
    public final static String MASK_DECIMAL3 = "Decimal 3";
    public final static String MASK_DECIMAL4 = "Decimal 4";
    public final static String MASK_CPF = "CPF";
    public final static String MASK_CNPJ = "CNPJ";
    public final static String MASK_CEP = "Cep";
    public final static String MASK_MERCADOLOGICO1 = "Mercadológico 1";
    public final static String MASK_MERCADOLOGICO2 = "Mercadológico 2";
    public final static String MASK_MERCADOLOGICO3 = "Mercadológico 3";
    public final static String MASK_MERCADOLOGICO4 = "Mercadológico 4";
    public final static String MASK_MERCADOLOGICO5 = "Mercadológico 5";
    public final static String MASK_NCM1 = "Ncm 1";
    public final static String MASK_NCM2 = "Ncm 2";
    public final static String MASK_NCM3 = "Ncm 3";
    public final static String MASK_CFOP = "CFOP";
    public final static String MASK_AUTOMACAO = "Automação";
    public final static String MASK_BIBLIOTECA_PDV = "Biblioteca PDV";
    public final static String MASK_HORA = "Hora";
    public final static String MASK_HORA_COMPLETA = "Hora Completa";
    public final static String MASK_CUSTO = "Custo";
    public final static String MASK_DUN14 = "Dun 14";
    public final static String MASK_TELEFONE = "Telefone";
    public final static String MASK_DESCONTO = "Desconto";
    public final static String MASK_CENTROCUSTO1 = "Centro Custo 1";
    public final static String MASK_CENTROCUSTO2 = "Centro Custo 2";
    public final static String MASK_CENTROCUSTO3 = "Centro Custo 3";
    public final static String MASK_SUFRAMA = "Inscrição Suframa";
    private MaskFormatter formato = new MaskFormatter();
    private String mascara = "";
    private int columns = 0;
    private boolean caixaAlta = true;
    private boolean selecionaTexto = true;
    private boolean negativo = false;
    private boolean teclaEnter = true;
    private String dataInicio = "";
    private Method consultaData = null;
    private boolean obrigatorio = false;
    private JPopupMenu popUp = new JPopupMenu();
    private LBPlainDocument plain = new LBPlainDocument();
    private UndoManager undo = new UndoManager();

    public LBTextField() {
        initComponents();

        this.mascara = MASK_TEXTO;
        setTeclaEnter(true);

        setDocument(plain);
        plain.addUndoableEditListener(undo);

        setDisabledTextColor(UIManager.getColor("TextField.foreground"));
    }

    @Override
    public int getColumns() {
        return columns;
    }

    public void setInt(int i_int) {
        this.setText(String.valueOf(i_int));
    }

    public void setLong(long i_long) {
        this.setText(String.valueOf(i_long));
    }

    @Override
    public void setColumns(int i_columns) {
        this.columns = i_columns;

        plain.setColumns(i_columns);
    }

    public void setCaixaAlta(boolean i_caixaAlta) {
        caixaAlta = i_caixaAlta;
        plain.setCaixaAlta(i_caixaAlta);
    }

    public boolean isCaixaAlta() {
        return caixaAlta;
    }

    public String getClipText() {
        if (getMascara().equals(MASK_DATA)) {
            return getText().replace(" ", "").replace("/", "");

        } else if (getMascara().equals(MASK_MESANO)) {
            return getText().replace(" ", "").replace("/", "");

        } else if (getMascara().equals(MASK_CPF)) {
            return getText().replace(" ", "").replace(".", "").replace("-", "");

        } else if (getMascara().equals(MASK_CNPJ)) {
            return getText().replace(" ", "").replace(".", "").replace("/", "").replace("-", "");

        } else if (getMascara().equals(MASK_CEP)) {
            return getText().replace(" ", "").replace("-", "");

        } else if ((getMascara().equals(MASK_MERCADOLOGICO1)) || (getMascara().equals(MASK_MERCADOLOGICO2)) || (getMascara().equals(MASK_MERCADOLOGICO3)) || (getMascara().equals(MASK_MERCADOLOGICO4)) || (getMascara().equals(MASK_MERCADOLOGICO5)) || (getMascara().equals(MASK_NCM1)) || (getMascara().equals(MASK_NCM2)) || (getMascara().equals(MASK_NCM3)) || (getMascara().equals(MASK_CFOP)) || (getMascara().equals(MASK_CENTROCUSTO1)) || (getMascara().equals(MASK_CENTROCUSTO2)) || (getMascara().equals(MASK_CENTROCUSTO3))) {
            return getText().replace(" ", "").replace(".", "");

        } else if (getMascara().equals(MASK_BIBLIOTECA_PDV)) {
            return getText().replace(" ", "").replace(".", "");

        } else if (getMascara().equals(MASK_HORA) || getMascara().equals(MASK_HORA_COMPLETA)) {
            return getText().replace(" ", "").replace(":", "");

        } else if (getMascara().equals(MASK_TELEFONE)) {
            return getText().replace(" ", "").replace("(", "").replace(")", "").replace("-", "");

        } else if (getMascara().equals(MASK_DESCONTO)) {
            return getText().replace(" ", "").replace(",", "").replace(".", "");

        } else {
            return getText();
        }
    }

    public String getMascara() {
        return mascara;
    }

    public void setMascara(String i_mascara) {
        try {
            String mascaraAnterior = this.mascara;
            this.mascara = i_mascara;

            formato.install(null);

            if (i_mascara.equals(MASK_TEXTO)) {
                plain.setAcceptedChars(LBPlainDocument.ALPHA_NUMERIC);
                setHorizontalAlignment(JTextField.LEADING);

            } else if (i_mascara.equals(MASK_NUMERO)) {
                setHorizontalAlignment(JTextField.LEADING);
                plain.setAcceptedChars(LBPlainDocument.NUMERIC);

                if (mascaraAnterior.equals(MASK_DECIMAL3) && !getText().equals("")) {
                    setDouble(getDouble());
                }

            } else if (i_mascara.equals(MASK_DATA)) {
                plain.setAcceptedChars(LBPlainDocument.ALPHA_NUMERIC);
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("##/##/####");
                formato.install(this);

            } else if (i_mascara.equals(MASK_TELEFONE)) {
                plain.setAcceptedChars(LBPlainDocument.ALPHA_NUMERIC);
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("(##) ####-####");
                formato.install(this);

            } else if (i_mascara.equals(MASK_MESANO)) {
                plain.setAcceptedChars(LBPlainDocument.ALPHA_NUMERIC);
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("##/####");
                formato.install(this);

            } else if (i_mascara.equals(MASK_DECIMAL0)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.FLOAT);
                plain.setCasaDecimal(0);

                if (mascaraAnterior.equals(MASK_DECIMAL3) && !getText().equals("")) {
                    setDouble(getDouble());
                }

            } else if (i_mascara.equals(MASK_DECIMAL1)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.FLOAT);
                plain.setCasaDecimal(1);

            } else if (i_mascara.equals(MASK_DECIMAL2)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.FLOAT);
                plain.setCasaDecimal(2);

            } else if (i_mascara.equals(MASK_DECIMAL3)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.FLOAT);
                plain.setCasaDecimal(3);

                if ((mascaraAnterior.equals(MASK_NUMERO) || mascaraAnterior.equals(MASK_DECIMAL0)) && !getText().equals("")) {
                    setDouble(getDouble());
                }
                
            } else if (i_mascara.equals(MASK_SUFRAMA)) {
                setColumns(9);
                setHorizontalAlignment(JTextField.LEADING);
                plain.setAcceptedChars(LBPlainDocument.NUMERIC);

            } else if (i_mascara.equals(MASK_DECIMAL4)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.FLOAT);
                plain.setCasaDecimal(4);

            } else if (i_mascara.equals(MASK_CNPJ)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("##.###.###/####-##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_CPF)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###.###-##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_CEP)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("#####-###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_NCM1)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("####");
                formato.install(this);

            } else if (i_mascara.equals(MASK_NCM2)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("####.##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_NCM3)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("####.##.##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_CFOP)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("#.###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_MERCADOLOGICO1)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_MERCADOLOGICO2)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_MERCADOLOGICO3)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###.###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_MERCADOLOGICO4)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###.###.###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_MERCADOLOGICO5)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###.###.###.###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_AUTOMACAO)) {
                setColumns(14);
                setHorizontalAlignment(JTextField.LEADING);
                plain.setAcceptedChars(LBPlainDocument.NUMERIC);

            } else if (i_mascara.equals(MASK_DUN14)) {
                setColumns(14);
                setHorizontalAlignment(JTextField.LEADING);
                plain.setAcceptedChars(LBPlainDocument.NUMERIC);

            } else if (i_mascara.equals(MASK_BIBLIOTECA_PDV)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("##.##.##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_HORA)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("##:##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_HORA_COMPLETA)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("##:##:##");
                formato.install(this);

            } else if (i_mascara.equals(MASK_CUSTO)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.FLOAT);
                plain.setCasaDecimal(3);

            } else if (i_mascara.equals(MASK_DESCONTO)) {
                setHorizontalAlignment(JTextField.RIGHT);
                plain.setAcceptedChars(LBPlainDocument.NUMERIC + "+");
                plain.setCasaDecimal(0);

            } else if (i_mascara.equals(MASK_CENTROCUSTO1)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_CENTROCUSTO2)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###");
                formato.install(this);

            } else if (i_mascara.equals(MASK_CENTROCUSTO3)) {
                setHorizontalAlignment(JTextField.LEADING);
                formato.setMask("###.###.###");
                formato.install(this);

            } else {
                plain.setAcceptedChars("");
                setHorizontalAlignment(JTextField.LEADING);
            }

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, "Atenção");
        }
    }

    public void requestFocusLater() {
        Runnable doFocus = new Runnable() {

            public void run() {
                requestFocus();
            }
        };

        SwingUtilities.invokeLater(doFocus);
    }

    private void validarData() throws Exception {
        if (getClipText().length() < 4) {
            int dia = Integer.parseInt(getClipText());

            if (this.dataInicio.isEmpty()) {
                if (this.consultaData != null) {
                    setText(Util.dateAdd((String) consultaData.invoke(this), "d", dia));
                } else {
                    throw new LBException("Data inválida!");
                }
            } else {
                setText(Util.dateAdd(this.dataInicio, "d", dia));
            }

        } else if (getClipText().length() == 6) {
            String data = new SimpleDateFormat("dd/MM/yy").format(new SimpleDateFormat("dd/MM/yy").parse(getText().trim()));

            if (!data.equals(getText().trim())) {
                throw new LBException("Data inválida!");
            }

            setText(Util.formatDataGUI(new SimpleDateFormat("dd/MM/yy").parse(getText().trim())));
        }

        if (!Util.isDataValida(getText())) {
            throw new LBException("Data inválida!");
        }
    }

    public void setParentSelected(boolean i_valor) throws Exception {
        Container oContainer = getParent();

        int i = 0;

        while (true) {
            oContainer = oContainer.getParent();

            if (oContainer instanceof LBInternalFrame) {
                ((LBInternalFrame) oContainer).setSelected(i_valor);
                break;
            }

            if (i > 10) {
                break;
            }

            i++;
        }
    }

    @Override
    public void setForeground(Color fg) {
        super.setForeground(fg);

        setDisabledTextColor(fg);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                formActionPerformed(evt);
            }
        });
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                formFocusLost(evt);
            }
        });
        addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                formInputMethodTextChanged(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                formKeyTyped(evt);
            }
        });
    }// </editor-fold>//GEN-END:initComponents

    private void formFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusLost
        try {
            if (negativo && getText().equals("-")) {
                setText("");
            }

            if (mascara.equals(MASK_DECIMAL0)) {
                if (!getText().equals("")) {
                    double valor = Double.parseDouble(getText());
                    setDouble(valor);
                }
            } else if (mascara.equals(MASK_DECIMAL1)) {
                if (!getText().equals("")) {
                    double valor = 0;

                    if ((getText().indexOf(".") == -1) && (getText().indexOf(",") == -1)) {
                        valor = Double.parseDouble(getText()) / 10;
                    } else {
                        if (!getText().equals(".") && !getText().equals(",")) {
                            valor = Double.parseDouble(getText().replace(",", "."));
                        }
                    }

                    plain.setColumns(0);
                    setDouble(valor);
                }
            } else if (mascara.equals(MASK_DECIMAL2)) {
                if (!getText().equals("")) {
                    double valor = 0;

                    if ((getText().indexOf(".") == -1) && (getText().indexOf(",") == -1)) {
                        valor = Double.parseDouble(getText()) / 100;
                    } else {
                        if (!getText().equals(".") && !getText().equals(",")) {
                            valor = Double.parseDouble(getText().replace(",", "."));
                        }
                    }

                    plain.setColumns(0);
                    setDouble(valor);
                }
            } else if (mascara.equals(MASK_DECIMAL3)) {
                if (!getText().equals("")) {
                    double valor = 0;

                    if ((getText().indexOf(".") == -1) && (getText().indexOf(",") == -1)) {
                        valor = Double.parseDouble(getText()) / 1000;
                    } else {
                        if (!getText().equals(".") && !getText().equals(",")) {
                            valor = Double.parseDouble(getText().replace(",", "."));
                        }
                    }

                    plain.setColumns(0);
                    setDouble(valor);
                }
            } else if (mascara.equals(MASK_DECIMAL4)) {
                if (!getText().equals("")) {
                    double valor = 0;

                    if ((getText().indexOf(".") == -1) && (getText().indexOf(",") == -1)) {
                        valor = Double.parseDouble(getText()) / 10000;
                    } else {
                        if (!getText().equals(".") && !getText().equals(",")) {
                            valor = Double.parseDouble(getText().replace(",", "."));
                        }
                    }

                    plain.setColumns(0);
                    setDouble(valor);
                }
            } else if (mascara.equals(MASK_DATA)) {
                if (!getClipText().equals("")) {
                    validarData();
                }
            } else if (mascara.equals(MASK_MESANO)) {
                if (!getClipText().equals("")) {
                    if (!Util.isMesAnoValido(getText())) {
                        throw new LBException("Data inválida!");
                    }
                }
            } else if (mascara.equals(MASK_HORA)) {
                if (!getClipText().equals("")) {
                    if (!Util.isHoraValida(getText())) {
                        throw new LBException("Hora inválida!");
                    }
                }
            } else if (mascara.equals(MASK_HORA_COMPLETA)) {
                if (!getClipText().equals("")) {
                    if (!Util.isHoraValida(getText())) {
                        throw new LBException("Hora inválida!");
                    }
                }
            } else if (mascara.equals(MASK_CNPJ)) {
                if (!this.getClipText().equals("")) {
                    if (!Util.isCNPJValido(this.getClipText())) {
                        throw new LBException("CNPJ inválido!");
                    }
                }
            } else if (mascara.equals(MASK_SUFRAMA)) {
                if (!this.getClipText().equals("")) {
                    if (!Util.isInscricaoSuframaValida(this.getClipText())) {
                        throw new LBException("Inscrição Suframa inválida!");
                    }
                }
            } else if (mascara.equals(MASK_CPF)) {
                if (!this.getClipText().equals("")) {
                    if (!Util.isCPFValido(this.getClipText())) {
                        throw new LBException("CPF inválido!");
                    }
                }
            } else if (mascara.equals(MASK_NCM1)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 4) {
                        throw new LBException("Ncm inválido!");
                    }
                }
            } else if (mascara.equals(MASK_NCM2)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 6) {
                        throw new LBException("Ncm inválido!");
                    }
                }
            } else if (mascara.equals(MASK_NCM3)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 8) {
                        throw new LBException("Ncm inválido!");
                    }
                }
            } else if (mascara.equals(MASK_CFOP)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 4) {
                        throw new LBException("CFOP inválido!");
                    }
                }
            } else if (mascara.equals(MASK_MERCADOLOGICO1)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 3) {
                        throw new LBException("Mercadológico inválido!");
                    }
                }
            } else if (mascara.equals(MASK_MERCADOLOGICO2)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 6) {
                        throw new LBException("Mercadológico inválido!");
                    }
                }
            } else if (mascara.equals(MASK_MERCADOLOGICO3)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 9) {
                        throw new LBException("Mercadológico inválido!");
                    }
                }
            } else if (mascara.equals(MASK_MERCADOLOGICO4)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 12) {
                        throw new LBException("Mercadológico inválido!");
                    }
                }
            } else if (mascara.equals(MASK_MERCADOLOGICO5)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 15) {
                        throw new LBException("Mercadológico inválido!");
                    }
                }
            } else if (mascara.equals(MASK_BIBLIOTECA_PDV)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 6) {
                        throw new LBException("Versão de Biblioteca inválido!");
                    }
                }
            } else if (mascara.equals(MASK_AUTOMACAO)) {
                if (!getText().equals("")) {
                    this.setText(Util.formatNumber(getLong(), 13));

                    //if (getLong() == 0 || (getText().length() == 14 && !Util.isDun14Valido(getLong())) || (getText().length() < 14 && !Util.isEan13Valido(getLong()))) {
                    //    throw new LBException("Código de barras inválido!");
                    //}
                }
            } else if (mascara.equals(MASK_DUN14)) {
                if (!getText().equals("")) {
                    this.setText(Util.formatNumber(getLong(), 14));

                    if (!Util.isDun14Valido(getLong()) || this.getLong() == 0) {
                        throw new LBException("Código Dun 14 inválido!");
                    }
                }
            } else if (mascara.equals(MASK_CUSTO)) {
                if (!getText().equals("")) {
                    double valor = 0;

                    if ((getText().indexOf(".") == -1) && (getText().indexOf(",") == -1)) {
                        valor = Double.parseDouble(getText()) / 100;
                    } else {
                        valor = Double.parseDouble(getText().replace(",", "."));
                    }

                    plain.setColumns(0);

                    setDouble(valor);
                }
            } else if (mascara.equals(MASK_CENTROCUSTO1)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 3) {
                        throw new LBException("Centro Custo inválido!");
                    }
                }
            } else if (mascara.equals(MASK_CENTROCUSTO2)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 6) {
                        throw new LBException("Centro Custo inválido!");
                    }
                }
            } else if (mascara.equals(MASK_CENTROCUSTO3)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 9) {
                        throw new LBException("Centro Custo inválido!");
                    }
                }
            } else if (mascara.equals(MASK_TELEFONE)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 10) {
                        throw new LBException("Telefone inválido!");
                    }
                }
            } else if (mascara.equals(MASK_CEP)) {
                if (!this.getClipText().equals("")) {
                    if (this.getClipText().length() != 8) {
                        throw new LBException("CEP inválido!");
                    }
                }
            }
        } catch (Exception ex) {
            Util.exibirMensagemErro(ex, "Atenção");

            Runnable doFocus = new Runnable() {

                public void run() {
                    requestFocus();
                }
            };

            SwingUtilities.invokeLater(doFocus);
        }
    }//GEN-LAST:event_formFocusLost

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
        if (mascara.equals(MASK_DECIMAL0)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        } else if (mascara.equals(MASK_DECIMAL1)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        } else if (mascara.equals(MASK_DECIMAL2)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        } else if (mascara.equals(MASK_DECIMAL3)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        } else if (mascara.equals(MASK_DECIMAL4)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        } else if (mascara.equals(MASK_CUSTO)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        } else if (mascara.equals(MASK_DESCONTO)) {
            if (!getText().equals("")) {
                setText(getText().replace(".", ""));
                plain.setColumns(getColumns());
            }
        }

        if (isEditable() && isSelecionaTexto()) {
            Runnable doSelect = new Runnable() {

                public void run() {
                    selectAll();
                }
            };

            SwingUtilities.invokeLater(doSelect);
        }

        if (!isEditable()) {
            selectAll();
        }
    }//GEN-LAST:event_formFocusGained

    private void formKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyTyped
    }//GEN-LAST:event_formKeyTyped

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        try {
            if (evt.getKeyCode() == KeyEvent.VK_F5) {
                if (this.mascara.equals(MASK_DATA)) {
                    if (this.consultaData != null) {
                        this.setText((String) consultaData.invoke(this));
                        this.transferFocus();
                    }

                } else if (this.mascara.equals(MASK_MESANO)) {
                    if (this.consultaData != null) {
                        this.setText(((String) consultaData.invoke(this)).substring(3));
                        this.transferFocus();
                    }

                } else if (this.mascara.equals(MASK_HORA) || this.mascara.equals(MASK_HORA_COMPLETA)) {
                    this.setText(Util.getHoraAtual());
                    this.transferFocus();
                }
            } else if (evt.getKeyCode() == KeyEvent.VK_F9) {
                if (this.mascara.equals(MASK_DECIMAL2)) {
//                    LBCalculadora form = new LBCalculadora();
//                    int x = this.getX();
//                    int y = this.getY() + this.getHeight();
//
//                    popUp.removeAll();
//                    popUp.add(form);
//                    popUp.setSize(form.getWidth(), form.getHeight());
//                    popUp.show(this, x, y);
                }
            }

            if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_Z) {
                if (undo.canUndo()) {
                    undo.undo();
                }
            } else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_Y) {
                if (undo.canRedo()) {
                    undo.redo();
                }
            }

        } catch (Exception ex) {
        }
    }//GEN-LAST:event_formKeyPressed

    private void formActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_formActionPerformed
    }//GEN-LAST:event_formActionPerformed

    private void formInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_formInputMethodTextChanged
    }//GEN-LAST:event_formInputMethodTextChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    public void setDouble(double d) {
        if (getMascara().equals(MASK_DECIMAL0)) {
            setText(new DecimalFormat("###,##0").format(Util.round(d, 0)));

        } else if (getMascara().equals(MASK_DECIMAL1)) {
            setText(new DecimalFormat("###,##0.0").format(Util.round(d, 1)));

        } else if (getMascara().equals(MASK_DECIMAL2)) {
            setText(new DecimalFormat("###,##0.00").format(Util.round(d, 2)));

        } else if (getMascara().equals(MASK_DECIMAL3)) {
            setText(new DecimalFormat("###,##0.000").format(Util.round(d, 3)));

        } else if (getMascara().equals(MASK_DECIMAL4)) {
            setText(new DecimalFormat("###,##0.0000").format(Util.round(d, 4)));

        } else if (getMascara().equals(MASK_NUMERO)) {
            setText(new DecimalFormat("###,##0").format(d));

        } else if (getMascara().equals(MASK_CUSTO)) {
            String valor = new DecimalFormat("###,##0.000").format(Util.round(d, 3));

            if ((valor.substring(valor.length() - 1, valor.length()).equals("0"))) {
                setText(new DecimalFormat("###,##0.00").format(Util.round(d, 2)));
            } else {
                setText(new DecimalFormat("###,##0.000").format(Util.round(d, 3)));
            }
        } else {
            setText(String.valueOf(d));
        }
    }

    public int getInt() throws Exception {
        if (this.getClipText().equals("")) {
            return 0;
        } else {
            return Integer.parseInt(this.getClipText());
        }
    }

    public long getLong() throws Exception {
        if (this.getClipText().equals("")) {
            return 0;
        } else {
            return Long.parseLong(this.getClipText());
        }
    }

    public double getDouble() throws Exception {
        if (this.getClipText().equals("")) {
            return 0;
        } else {
            if ((getText().indexOf(".") == -1) && (getText().indexOf(",") == -1)) {
                double valor = 0;

                if (mascara.equals(MASK_DECIMAL0) || mascara.equals(MASK_NUMERO)) {
                    valor = Double.parseDouble(getText());

                } else if (mascara.equals(MASK_DECIMAL1)) {
                    valor = Double.parseDouble(getText()) / 10;

                } else if (mascara.equals(MASK_DECIMAL2) || mascara.equals(MASK_CUSTO)) {
                    valor = Double.parseDouble(getText()) / 100;

                } else if (mascara.equals(MASK_DECIMAL3)) {
                    valor = Double.parseDouble(getText()) / 1000;

                } else if (mascara.equals(MASK_DECIMAL4)) {
                    valor = Double.parseDouble(getText()) / 10000;
                }

                return valor;

            } else {
                return Double.parseDouble(getText().replace(".", "").replace(",", "."));
            }
        }
    }

    public boolean isSelecionaTexto() {
        return selecionaTexto;
    }

    public void setSelecionaTexto(boolean selecionaTexto) {
        this.selecionaTexto = selecionaTexto;
    }

    public boolean isNegativo() {
        return negativo;
    }

    public void setNegativo(boolean negativo) {
        this.negativo = negativo;
        plain.setNegativo(negativo);
    }

    public boolean isTeclaEnter() {
        return teclaEnter;
    }

    public void setTeclaEnter(boolean teclaEnter) {
        this.teclaEnter = teclaEnter;

        HashSet kTab = new HashSet(1);
        kTab.add(KeyStroke.getKeyStroke("TAB"));

        if (teclaEnter) {
            kTab.add(KeyStroke.getKeyStroke("ENTER"));
        }

        setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, kTab);
    }

    public String getDataInicio() {
        return dataInicio;
    }

    public void setDataInicio(String dataInicio) {
        this.dataInicio = dataInicio;
    }

    public void setConsultaData(Method consultaData) {
        this.consultaData = consultaData;
    }

    public boolean isObrigatorio() {
        return obrigatorio;
    }

    public void setObrigatorio(boolean obrigatorio) {
        this.obrigatorio = obrigatorio;

        if (this.isEnabled()) {
            if (obrigatorio) {
                this.setBackground(Util.COR_OBRIGATORIO);
            } else {
                this.setBackground(UIManager.getColor("TextField.background"));
            }
        } else {
            this.setBackground(UIManager.getColor("TextField.disabledBackground"));
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);

        setObrigatorio(obrigatorio);
    }

    @Override
    public void setEditable(boolean b) {
        super.setEditable(b);

        setObrigatorio(obrigatorio);
    }
}
